const express = require('express')
const router = express.Router()
const xss = require('node-xss').clean;
const acticleAction = require('../Controller/acticle')
const checkAuthority =require('../Controller/authority')
const check = require('../mid')


//新文章页面
router.get('/add-acticle',check.isLogin, function (req, res) {
  acticleAction.home(function(user,cate){
    console.log(cate,user)
    if(user&&cate){
      res.render('add-acticle.html',{user,cate})
    }
  })
})


//添加新文章
router.post('/add-acticle',check.isLogin, function (req, res) {
  let session =req.session.user
  let check = checkAuthority(session,'article')
  let arctiles= req.body
  if(!arctiles.createAt){
    arctiles.createAt = new Date()
  }
  let toastinfo = {
    "type": "success",
    "info": "《" + arctiles.title +"》保存成功"
  }
  acticleAction.add(arctiles,function(user,cate,actile,taginfo){
    setTimeout(function(){
    res.render('add-acticle.html',{user,cate,toastinfo,check})
    },2000)
})
})
//渲染所有文章页面
router.get('/manage-acticle',check.isLogin, function (req, res) {
  res.render('manage-acticle.html')
})

// 渲染编辑页面
router.get('/edit-acticle:id',check.isLogin, function (req, res) {
  let session =req.session.user
  let check = checkAuthority(session,'article')
  let id = req.params.id
  acticleAction.arcById(id,function(user,cate,actile,taginfo){
    let toastinfo = {
      "type": "info",
      "info": "正在编辑 《" + actile.title +"》"
    }
    res.render('edit-acticle.html',{user,cate,actile,toastinfo,check,taginfo})
  })
})

//修改文章
router.post('/edit-acticle:id',check.isLogin,check.canTop,function(req,res){
   let session =req.session.user
   let check = checkAuthority(session,'article')
   let id = req.params.id
   let oldactile=req.body
  acticleAction.edit(id,oldactile,function(user,cate,actile,taginfo){
        let toastinfo = {
          "type": "success",
          "info": "《" + actile.title +"》编辑成功"
        }
        setTimeout(function(){
          res.render('edit-acticle.html',{user,cate,actile,toastinfo,check,taginfo})
          },2000)
  })
})

//删除文章
router.get('/deletearc:id',check.isLogin,check.isPower2,function(req,res){
  let session =req.session.user
  checkAuthority(res,session,'user')
  let id = req.params.id
  acticleAction.delete(id,function(stat){
    if(stat){
      res.redirect('/admin/manage-acticle')
    }
  })
})

//异步api
router.get('/getArticleList',function(req,res){
  acticleAction.all(function(arctileList){
    res.json(arctileList)
  })
})


module.exports = router